package taskvalidator

import (
	"errors"
	"fmt"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/model"
	"yunj/pkg/yunj/app/service/admin/adminservice"
	validatorUtil "yunj/pkg/yunj/core/validator/util"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Task struct {
	validate.Validator
}

func (v *Task) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "TableEvent" {
		err = v.HandleDatasByTableEvent(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Task) HandleDatasByTableEvent(datas map[string]interface{}) (err error) {
	pks := util.MapKeyValue(datas, "pks", []any{})
	if len(pks) == 0 {
		err = errors.New("请勾选要处理的数据")
		return
	}
	ginContext := validatorUtil.GetDatasBuilderGinContext(datas)
	if ginContext == nil {
		err = errors.New("未知异常，请刷新页面后重试")
		return
	}
	// 如果不能查看其它管理员的任务，则需要判断事件任务所有者是否当前管理员
	if !adminservice.CheckAuth(ginContext, "yunj_task_list_filter_member") {
		memberId := adminservice.GetLoginMemberId(ginContext)
		if memberId <= 0 {
			err = errors.New("请登录后，执行此操作！")
			return
		}
		var existsIds []any
		if err = global.MySQL.Model(&model.AdminTask{}).Where("id in ? and member_id = ?", pks, memberId).Pluck("id", &existsIds).Error; err != nil {
			err = fmt.Errorf("查询当前操作任务所属权限数据异常！%v", err)
			return
		}
		if !util.SliceIn(existsIds, pks) {
			err = errors.New("当前任务不为当前登录成员所有，请刷新页面后重试！")
			return
		}
	}
	return
}
